import { reqLogin, reqGetUserInfo, reqGetUserDetailInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToKen(state, newToken) {
    // 1.存vuex
    state.token = newToken
    // 2.本地存储
    setToken(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = ''
  }
}

const actions = {
  async login(context, loginForm) {
    const { data: token } = await reqLogin(loginForm)
    context.commit('setToKen', token)
  },
  async getUserInfo(context) {
    const { data: data1 } = await reqGetUserInfo()
    const { data: data2 } = await reqGetUserDetailInfo(data1.userId)
    const data = { ...data1, ...data2 }
    // const data = Objectπ.assign(data1, data2)
    console.log(data)
    context.commit('setUserInfo', data)
    return data
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

